package com.lee.bemorebetter.degin.principle;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author ：liylw
 * @date ：Created in 2021/3/25 15:35
 */
@Slf4j
public class ConsoleReporter {
    private MetricsStorage metricsStorage;
    private ScheduledExecutorService executor;

    public ConsoleReporter(MetricsStorage metricsStorage) {
        this.metricsStorage = metricsStorage;
        executor = new ScheduledThreadPoolExecutor(1, r -> {
            Thread thread = new Thread(r);
            thread.setName("ConsoleReporter-Thread-");
            return thread;
        });
    }


    public void startRepeatedReport(long periodInSeconds,long durationInSeconds){
        executor.scheduleAtFixedRate(()->{
            long durationInMills = durationInSeconds * 1000;
            long endTimeInMills = System.currentTimeMillis();
            long startTimeInMillis = endTimeInMills - durationInMills;
            Map<String, List<RequestInfo>> requestInfos = metricsStorage.getRequestInfos(startTimeInMillis, endTimeInMills);
            Map<String,RequestStat> stats = new HashMap<>();
            for (Map.Entry<String, List<RequestInfo>> stringListEntry : requestInfos.entrySet()) {
                String apiName = stringListEntry.getKey();
                List<RequestInfo> requestInfoPerApi = stringListEntry.getValue();
                RequestStat aggregate = Aggregator.aggregate(requestInfoPerApi, durationInMills);
                stats.put(apiName,aggregate);
            }
            log.info("Time Span: [{} ,{}, ",startTimeInMillis,endTimeInMills);
            Gson gson = new Gson();
            log.info(gson.toJson(stats));
        },0,periodInSeconds, TimeUnit.SECONDS);
    }
}
